package com.hzf.wxplatform.web.utils;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.hzf.common.util.CheckCode;
import com.hzf.common.util.PropertiesFileUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import javax.annotation.PostConstruct;
import java.util.HashMap;

public class SMSUtils {
    /**
     * 日志
     */
    private static Logger logger = LogManager.getLogger(SMSUtils.class);

    /**
     * 容联 云通讯账号
     */
    private static String ytxAccountSID = PropertiesFileUtil.getInstance("hzf-sms").get("yuntongxun.ACCOUNT.SID");

    private static String ytxAuthToken= PropertiesFileUtil.getInstance("hzf-sms").get("yuntongxun.AUTH.TOKEN");

    private static String ytxRestServerHost= PropertiesFileUtil.getInstance("hzf-sms").get("yuntongxun.Rest.Server.host");

    private static String ytxRestServerPort= PropertiesFileUtil.getInstance("hzf-sms").get("yuntongxun.Rest.Server.port");

    private static String ytxAppID= PropertiesFileUtil.getInstance("hzf-sms").get("yuntongxun.AppID");

    private static String ytxDefaultSMSTemplate= PropertiesFileUtil.getInstance("hzf-sms").get("yuntongxun.sms.tempate");

    private static boolean useDefaultCode= false;

    // 容联*云通讯短息发送
    private static CCPRestSmsSDK restAPI = new CCPRestSmsSDK(); //初始化SDK

    @PostConstruct
    public static void init() {

        // 1. 短信推送服务器初始化
        try {
            restAPI.init(ytxRestServerHost, ytxRestServerPort);
            restAPI.setAccount(ytxAccountSID, ytxAuthToken);
            restAPI.setAppId(ytxAppID);
        } catch (Exception e) {
            logger.error("短息推送服务器初始化失败：", e);
        }
    }
    public static CheckCode sendCheckCode(String to) {
        System.out.println(to);
        init();
        // 1. 生成验证码
        CheckCode checkCode = createCheckCode(to);

  /*      HashMap<String, Object> response = null;
        if (useDefaultCode) {
            response = new HashMap<>(1);
            response.put("statusCode","000000");
        }else {
            String[] datas = new String[]{checkCode.getCode(), "1"};
            response = restAPI.sendTemplateSMS(to, ytxDefaultSMSTemplate, datas
            );
        }
        System.out.println(response);
        System.out.println(response.get("statusCode"));
        // 如果短信推送的返回码为000000，则表示成功，否则为失败
        if (!StringUtils.equals("000000", (String) response.get("statusCode"))) {
            checkCode = null;
        }*/
        return checkCode;
    }


    /**
     * 生成验证码
     *
     * @return
     */
    private static CheckCode createCheckCode(String mobile) {

        String code = useDefaultCode ? "1234" : RandomStringUtils.randomNumeric(4);
        CheckCode checkCode = new CheckCode();
        checkCode.setCode(code);
        checkCode.setMobile(mobile);
        checkCode.setCreateTime(System.currentTimeMillis());

        return checkCode;
    }
}
